package com.example.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.example.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    // 路径匹配器
    public static final AntPathMatcher pathMatcher = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String url = request.getRequestURI();

        if (check(url)) {
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            if (request.getSession().getAttribute("employee") != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            }else {
                response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
            }
        }
    }

    public boolean check(String url) {
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "front/**",
        };
        for (String u : urls) {
            if (pathMatcher.match(u, url)) {
                return true;
            }
        }
        return false;

    }

}
